﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Chaos.messages
{
    public class process_user_info : message
    {    
        String m_user;
        public String User
        {
            get { return m_user; }
            set { m_user = value; }
        }

        String validateusername(network.gameserver server, String name)
        {
            String valid = name;
            int i = 1;
            while (server.findconnectionbyuser(valid) != null)
            {
                valid = name + i;
                i++;
            }
            return valid;
        }

        public override void process(context in_context)
        {
            network.gameserver s = System.Windows.Application.Current.FindResource("game_server") as network.gameserver;
            if (s != null)
            {
                String name = validateusername(s, User);
                in_context.Connection.User = name;

                if (name != User)
                {
                    process_user_info_change message = new process_user_info_change();
                    message.User = name;
                    in_context.Connection.sendmessage(message);
                }

                ProcessUserInfoEvent e = new ProcessUserInfoEvent();
                e.User = name;
                System.Windows.Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
                    new OnProcessUserInfoDelegate(OnProcessUserInfoUIThread), e);
            }
        }

        public override void serialize(stream.stream in_Stream)
        {
            in_Stream.begin("process_user_info")
                .serialize("user", ref m_user)
            .end();
        }

        public class ProcessUserInfoEvent : EventArgs
        {
            public String User { get; set; }
            public ProcessUserInfoEvent()
            {
            }
        };
        public delegate void OnProcessUserInfoDelegate(ProcessUserInfoEvent e);

        public void OnProcessUserInfoUIThread(ProcessUserInfoEvent e)
        {
            model.appinfo a = System.Windows.Application.Current.FindResource("model_appinfo") as model.appinfo;
            if (a != null)
            {
                if (a.findbyname(e.User) == null)
                {
                    a.createplayer(e.User);
                }
            }                        
        }
    }
}
